<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onTableRefresh('keyword', onRefresh)">
		<el-row style="height: 100%" type="flex">
			<cl-biz-toolbar v-model="currBiz.biz_id" show-hq @change="bizChange" />
			<cl-flex1 class="h-100" style="overflow: hidden">
				<cl-pagefull @resize="onResize">
					<template #head>
						<el-row type="flex">
							<div class="title" style="width: 150px;">{{ currBiz.biz_name }}</div>
							<cl-flex1 />
							<div>
								<cl-filter-group v-model="search" class="pr-1">
									<cl-filter label="关键字">
										<el-input
											v-model="search.keyword"
											placeholder="员工姓名/手机号"
											clearable
											style="width: 200px"
											@change="refresh()"
										/>
									</cl-filter>
									<cl-filter label="部门/门店">
										<cl-cascader
											clearable
											v-model="search.dept_ids"
											:options="deptList"
											collapse-tags
											style="min-width: 230px"
											:props="{
												multiple: true,
												value: 'dept_id',
												label: 'dept_name'
											}"
											filterable
											@change="refresh()"
										/>
									</cl-filter>
									<cl-filter label="权限">
										<cl-select
											v-model="search.role_id"
											filterable
											clearable
											@change="refresh()"
										>
											<el-option label="全部" value="" />
											<el-option
												v-for="item in roleList"
												:key="item.ro_id"
												:label="item.ro_name"
												:value="item.ro_id"
											/>
										</cl-select>
									</cl-filter>
									<cl-filter label="状态">
										<cl-select
											v-model="search.status"
											placeholder="请选择状态"
											style="width: 120px"
											filterable
										>
											<el-option label="全部" value="" />
											<el-option
												v-for="(item, index) in statusList"
												:key="index"
												:label="item.label"
												:value="item.value"
											/>
										</cl-select>
									</cl-filter>
								</cl-filter-group>
								<!-- <el-button
									icon="el-icon-refresh"
									type="primary"
									@click="syncWorkWechat"
									:loading="syncing"
								>
									同步企业微信员工
								</el-button> -->
								<el-button icon="el-icon-plus" size="small" type="primary" @click="openForm()">
									新增员工
								</el-button>
							</div>
						</el-row>
					</template>
					<!-- 数据表格 -->
					<div style="height: 100%" ref="tableBox">
						<cl-table
							v-bind="table"
							:props="{
								maxHeight: this.tableHeight
							}"
						>
							<cl-empty slot="empty" />
							<template #column-mobile="{ scope: { row } }">
								{{ row.mobile }}
								<!-- <el-tag class="ml-1" v-if="row.wxk_exists == 1">
									已同步企业微信
								</el-tag> -->
							</template>
							<template #column-status="{ scope: { row } }">
								<el-tag :type="row.status != 1 ? 'danger' : ''">
									{{ row.status | constFilter("STAFF_STATUS") }}
								</el-tag>
							</template>
							<template #column-teacher_post="{ scope: { row } }">
								{{ row.teacher_post | constFilter("TEACHER_POST_LIST") }}
							</template>
							<template #column-opt="{ scope: { row } }">
								<div class="flex flex-align-start" v-if="row.is_super != 1">
									<el-button type="success" v-if="row.status == 99" @click="openDimissionRecover(row)"> 离职恢复 </el-button>
									<el-button type="primary" @click="edit(row)" v-else> 修改 </el-button>
									<el-button type="danger" @click="copy(row)"> 复制 </el-button>
									<el-dropdown
										class="ml-1"
										size="medium"
										@command="command => onCommand(command, row)"
									>
										<el-button>
											更多<i class="el-icon-arrow-down el-icon--right" />
										</el-button>
										<el-dropdown-menu slot="dropdown" style="min-width: 110px">
											<el-dropdown-item
												v-for="item in moreOptList"
												:key="item.command"
												:command="item.command"
											>
												{{ item.label }}
											</el-dropdown-item>
										</el-dropdown-menu>
									</el-dropdown>
								</div>
							</template>
						</cl-table>
					</div>
					<template #foot>
						<el-row type="flex">
							<cl-flex1 />
							<zm-pagination />
						</el-row>
					</template>
				</cl-pagefull>
			</cl-flex1>
		</el-row>
		<cl-staff-form ref="form" @confirm="staffRefresh" />
		<template v-for="item in moreOptList">
			<component
				v-if="!item.hide"
				:key="item.command"
				:is="toLowerLine(item.command)"
				:ref="item.command"
				@confirm="refresh"
			>
			</component>
		</template>
		<!-- 离职恢复 -->
		<dimission-recover ref="dimissionRecover" @confirm="refresh"></dimission-recover>
	</cl-crud>
</template>

<script>
import { mapGetters } from "vuex";
import constant from '@/constant'
// 门店表单
// import StaffForm from "./components/staff/staff-form";
// 调部门
import AdjustDept from "./components/staff/adjust-dept";
// 加微号
import AddWechat from "./components/staff/add-wechat";
// 管理事业部
import ManageCompany from "./components/staff/manage-company";
// 管理品牌
import ManageBrand from "./components/staff/manage-brand";
// 管理门店
import ManageStore from "./components/staff/manage-store";
// 管理部门
import ManageDept from "./components/staff/manage-dept";
// 管理渠道
import ManageChannel from "./components/staff/manage-channel";
//管理分公司
import ManageBranch from "./components/staff/manage-branch";
//离职恢复
import DimissionRecover from "./components/staff/dimission-recover";
import { delEmptyChildren } from "@/utils";
const menuList = [
	{ label: "调部门", command: "adjustDept" },
	{ label: "查看绑定加微号", command: "addWechat" },
	{ label: "管理分公司", command: "manageBranch" },
	{ label: "管理品牌", command: "manageBrand" },
	{ label: "管理门店", command: "manageStore" },
	{ label: "管理部门", command: "manageDept" },
	{ label: "管理渠道", command: "manageChannel" },
	{ label: "离职", command: "dimission", hide: true },
	{ label: "重置密码", command: "resetPassword", hide: true }
];
export default {
	name: "CrmPersonnelStaff",
	components: {
		// StaffForm,
		AdjustDept,
		AddWechat,
		ManageCompany,
		ManageBrand,
		ManageStore,
		ManageDept,
		ManageChannel,
		ManageBranch,
		DimissionRecover
	},
	data() {
		return {
			statusList: constant.STAFF_STATUS,

			// 表格配置
			table: {
				"context-menu": ["refresh"],
				columns: [
					{ type: "index", label: "#", align: "center", width: 50, fixed: true },
					{
						label: "员工名称",
						prop: "user_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "所属部门",
						prop: "dept_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true
					},
					{ label: "员工性别", prop: "sex_name", width: 90 },
					{ label: "手机号(账号)", prop: "mobile", width: 150 },
					{ label: "技师岗位", prop: "teacher_post", width: 100 },
					{
						label: "权限",
						prop: "ro_name",
						minWidth: 100,
						align: "left",
						showOverflowTooltip: true
					},
					{ label: "状态", prop: "status", width: 100 },
					{ label: "操作", prop: "opt", width: 230, fixed: "right" }
				]
			},
			search: {
				keyword: "", // 关键字
				dept_ids: [], //部门id
				role_id: ""
				// status: ""
			},
			currBiz: {},
			tableHeight: 0,
			load: false,
			deptList: [],
			roleList: [],
			// 同步中
			syncing: false
		};
	},
	computed: {
		...mapGetters(["userInfo"]),
		moreOptList() {
			const newMenuList = _.cloneDeep(menuList);
			if (this.userInfo?.biz_id == 1 && this.currBiz?.biz_id == 1) {
				newMenuList.splice(2, 0, { label: "管理事业部", command: "manageCompany" });
				return newMenuList;
			} else {
				return newMenuList;
			}
		}
	},
	created() {
		this.initData();
	},
	methods: {
		toLowerLine(str) {
			return str.replace(/[A-Z]/g, match => "-" + match.toLowerCase());
		},
		onResize(h) {
			this.tableHeight = h;
		},
		onLoad({ ctx, app }) {
			ctx.service(this.$service.user).done();
			if (!this.load) return;
			app.refresh(this.search);
		},
		async onRefresh(params, { next, done, render }) {
			const { biz_id } = this.currBiz;
			let { list } = await next({
				...params,
				biz_id
			});
			render(list);
		},
		// crud刷新
		refresh(biz_id, reset = true) {
			biz_id && (this.currBiz.biz_id = biz_id);
			let params = { ...this.search };
			if (reset) {
				params.page = 1;
			}
			this.$refs.crud.refresh(params);
			this.load = true;
		},
		//新增员工回调
		staffRefresh(biz_id, user_id, reset) {
			this.refresh(biz_id, reset);
			user_id && this.onCommand("manageBrand", { user_id }, true);
		},
		// 切换事业部
		bizChange(v) {
			this.currBiz = v;
			this.search.keyword = "";
			this.search.dept_ids = [];
			this.$nextTick(() => {
				this.getDeptList();
				this.getRoleList();
				this.refresh();
			});
		},
		// 部门
		async getDeptList() {
			const { biz_id } = this.currBiz;
			this.deptList = [];
			if (!biz_id) return;
			let data = await this.$service.dept.list({
				parent_id: 0,
				// is_store: 1,
				biz_id
			});
			delEmptyChildren(data);
			this.deptList = data;
		},
		// 权限组列表
		async getRoleList() {
			const { biz_id } = this.currBiz;
			this.roleList = [];
			const data = await this.$service.role.list({
				status: 1,
				biz_id
			});
			this.roleList = (data || []).filter(v => v.is_super != 1);
		},
		// 更多
		onCommand(command, row, isAssign = false) {
			if (command == "dimission") {
				this.dimission(row);
				return;
			}
			if (command == "resetPassword") {
				this.resetPassword(row);
				return;
			}
			this.$refs[command][0].open(row, isAssign);
		},
		// 离职员工恢复
		async openDimissionRecover(row) {
			this.$refs.dimissionRecover.open(row)
		},
		// 同步企业微信员工
		async syncWorkWechat() {
			const { biz_id } = this.currBiz;
			this.syncing = true;
			try {
				await this.$service.workwechat.syncUser({ biz_id }).done(() => {
					this.syncing = false;
					this.$message.success("同步成功！");
				});
				this.refresh(null, false);
			} catch (e) {
				this.$message.error(e || e?.msg || "同步失败！");
			}
		},
		openForm(type = "add", data) {
			this.$refs.form.open(type, data);
		},
		//复制
		copy(row) {
			this.openForm("copy", row);
		},
		//编辑
		edit(row) {
			this.openForm("edit", row);
		},
		// 删除
		dimission({ user_id }) {
			this.confirm()
				.then(async () => {
					await this.$service.user.remove({ user_id });
					this.$message.success("操作成功");
					this.refresh();
				})
				.catch(() => {});
		},
		// 重置员工密码
		resetPassword({ user_id }) {
			this.confirm()
				.then(async () => {
					await this.$service.user.resetUserPwd({ user_id });
					this.$message.success("操作成功");
					// this.refresh();
				})
				.catch(() => {});
		},
		initData() {
			this.getDeptList();
			this.getRoleList();
		}
	}
};
</script>
<style lang="scss" scoped>
.title {
	font-size: 18px;
}
</style>
